package com.winit.core.websocket.handler;

import com.winit.common.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * websocket消息处理类
 * @author wangjian
 *
 */
@Component
public class DefaultHandler implements WebSocketHandler {

	private static final Logger logger = LoggerFactory.getLogger(DefaultHandler.class);
	
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
			throws Exception {

		logger.info("websocket connection closed......");
		this.closeSocket(session);
	}

	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		logger.info("connect to the websocket success......");
	}

	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
			throws Exception {
		String mess = (String) message.getPayload();
		if(!StringUtils.isEmpty(mess)){
			if("closeThread".equals(mess)){
				this.closeSocket(session);
			}else if(mess.startsWith("tokenId:")){
				String tokenId = mess.replace("tokenId:","");
				logger.info("连接websocket,tokenId="+tokenId);
				session.getAttributes().put(Constants.WEBSOCKET_SESSION_USERNAME_INDEX,tokenId);
			}
		}
	}

	public void handleTransportError(WebSocketSession session, Throwable exception)
			throws Exception {
		logger.info("websocket connection closed......");
		if(session.isOpen()){
			session.close();
        }
		this.closeSocket(session);
	}

	public boolean supportsPartialMessages() {
		return false;
	}
    
	private void closeSocket(WebSocketSession session){
	}
}
